import {
  Body,
  Controller,
  forwardRef,
  Inject,
  Post,
  Request,
  UseGuards,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { UserService } from '@/modules/user/user.service';
import { RoleService } from '@/modules/role/role.service';
import { LocalAuthGuard } from './local-auth.guard';
import { LoginAuthDto } from './dto/login.dto';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';

@ApiTags('登录模块')
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @Inject(forwardRef(() => RoleService))
    private readonly roleService: RoleService,
  ) {}

  @ApiOperation({ summary: '登录' })
  @ApiResponse({ type: LoginAuthDto })
  @Post('login')
  @UseGuards(LocalAuthGuard) // 校验用户名密码，成功则追加 req.user 用户信息
  async login(@Request() req, @Body() LoginAuthDto: LoginAuthDto) {
    const { token } = await this.authService.login(req.user);
    const result = await this.userService.findOne(req.user.id);
    const reqData: any = {
      userInfo: {
        ...result,
        power: [],
      },
      token,
    };
    if (result.role) {
      const power = await this.roleService.findOne(result.role?.id);
      reqData.userInfo.power = power?.permissions || [];
    }
    console.log('reqData >>>', reqData);
    return reqData;
  }
}
